package com.zxn.project.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxn.project.pojo.HealthCode;
import com.zxn.project.pojo.ItineraryCode;
import com.zxn.project.pojo.R;
import com.zxn.project.service.ItineraryCodeService;
import com.zxn.project.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.Month;
import java.util.List;

@RestController()
@RequestMapping("/ItineraryCode")
public class ItineraryCodeController {

    @Autowired
    ItineraryCodeService itineraryCodeService;

    @PostMapping("/upload")
    public R uploadImage(@RequestBody ItineraryCode itineraryCode,@RequestHeader String token) throws Exception {
        String openid= JSON.parseObject(JwtUtil.parseJWT(token).getSubject()).get("openid").toString();

        itineraryCodeService.save(itineraryCode);
        return R.success("上传成功");
    }

    @GetMapping("/selectByTime")
    public R selectByTime(@RequestHeader String token) throws Exception {
        String openid= JSON.parseObject(JwtUtil.parseJWT(token).getSubject()).get("openid").toString();

        LambdaQueryWrapper<ItineraryCode> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime date = LocalDateTime.now();
        int year = date.getYear();
        Month month = date.getMonth();
        int dayOfMonth = date.getDayOfMonth();
        LocalDateTime dataStart = LocalDateTime.of(year, month, dayOfMonth, 0, 0, 0);
        LocalDateTime dataEnd = LocalDateTime.of(year, month, dayOfMonth, 23, 59, 59);
        queryWrapper.eq(ItineraryCode::getOpenid,openid);
        queryWrapper.gt(ItineraryCode::getUploadTime,dataStart);
        queryWrapper.lt(ItineraryCode::getUploadTime,dataEnd);

        List<ItineraryCode> list = itineraryCodeService.list(queryWrapper);

        return R.success(list);
    }



    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, @RequestHeader String token) throws Exception {
        String openid= JSON.parseObject(JwtUtil.parseJWT(token).getSubject()).get("openid").toString();
        //分页构造器
        Page<ItineraryCode> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<ItineraryCode> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByAsc(ItineraryCode::getUploadTime);

        queryWrapper.eq(ItineraryCode::getOpenid,openid);

        //分页查询
        itineraryCodeService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }
}
